import { createSlice, type PayloadAction, type Slice } from "@reduxjs/toolkit";
import type { CustomerData } from "../type/CustomerState";

const customerSlice: Slice<{ customer: CustomerData[] }> = createSlice({
    name: 'customer',
    initialState: {
        customer: localStorage.customer ? JSON.parse(localStorage.customer) : [] as CustomerData[]
    },
    reducers: {
        saveCustomerData: (state, action) => {
            state.customer = [...state.customer, action.payload];
            localStorage.customer = JSON.stringify(state.customer);
        },
        clearCustomerData: (state, action) => {
            state.customer = state.customer.filter((item) => item.id !== action.payload);
            localStorage.customer = JSON.stringify(state.customer);
        },
        updateCustomerData: (state, action: PayloadAction<{ id: string; data: CustomerData }>) => {
            const { id, data } = action.payload;
            state.customer = state.customer.map((item) => item.id == id ? { ...item, ...data } : item);
            localStorage.customer = JSON.stringify(state.customer);
        },
    }
})

export const { saveCustomerData, clearCustomerData, updateCustomerData } = customerSlice.actions;
export default customerSlice
